import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from 'path';
// Fix CJS/ESM interop for vite-plugin-monaco-editor-nls default export
import MonacoEditorNls from 'vite-plugin-monaco-editor-nls';
const { default: MonacoEditorNlsPlugin, esbuildPluginMonacoEditorNls, Languages: MonacoEditorNlsLanguages } = MonacoEditorNls;
// Load zh-hans locale data directly from plugin's bundled JSON to avoid path issues
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const zhHansLocale = require('vite-plugin-monaco-editor-nls/dist/locale/src/locale/zh-hans.json');

const host = process.env.TAURI_DEV_HOST;

// https://vitejs.dev/config/
export default defineConfig(async () => ({
  base: './',
  plugins: [
    vue({
      template: {
        compilerOptions: {
          vapor: true,
        },
      },
    }),
    // Force Monaco Editor UI locale to Simplified Chinese
    MonacoEditorNlsPlugin({ 
      locale: MonacoEditorNlsLanguages.zh_hans,
      localeData: zhHansLocale,
    }),
  ],

  // Ensure optimize-deps uses the same NLS locale during pre-bundling
  optimizeDeps: {
    esbuildOptions: {
      plugins: [
        esbuildPluginMonacoEditorNls({ 
          locale: MonacoEditorNlsLanguages.zh_hans,
          localeData: zhHansLocale,
        }),
      ],
    },
  },

  // Path aliases
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
    },
  },

  // 明确构建与 worker 选项，确保在 WebView2 环境兼容
  build: {
    target: ['es2020'],
    sourcemap: false,
  },
  worker: {
    format: 'es',
  },

  // Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
  //
  // 1. prevent vite from obscuring rust errors
  clearScreen: false,
  // 2. tauri expects a fixed port, fail if that port is not available
  server: {
    port: 1420,
    strictPort: true,
    host: host || false,
    hmr: host
      ? {
          protocol: "ws",
          host,
          port: 1421,
        }
      : undefined,
    watch: {
      // 3. tell vite to ignore watching `src-tauri`
      ignored: ["**/src-tauri/**"],
    },
  },
}));
